//
//  YZRegisterVM.m
//  VET
//
//  Created by Lam BG on 2018/7/2.
//  Copyright © 2018年 YZ. All rights reserved.
//

#import "YZRegisterVM.h"

#import "YZUser.h"

#import "YZSignAPI.h"

#import "YZActionSheet.h"

#import "OpenShareHeader.h"

#import "NSString+Predicate.h"

@implementation YZRegisterVM

- (instancetype)init {
    
    if (self = [super init]) {
        
        [self setup];
    }
    
    return self;
}

- (void)setup {

    @weakify(self)
    // 手机号码
    [[RACObserve(self, number) distinctUntilChanged] subscribeNext:^(NSString *number) {

        @strongify(self)
        if ([number isValidMobileNumber]) {

            // 发起验证号码请求
            [SVProgressHUD show];
            [[YZSignAPI apiCheckUserMobile:number] subscribeNext:^(id  _Nullable x) {

                [SVProgressHUD dismiss];
                BOOL isExist = [x boolValue];
                if (isExist) {
                    
                    // 号码存在被注册过
                    self.numberWarningInfo = @"该手机号码已注册";
                } else {
                    
                    // 号码不存在 可以注册
                }
                self.canVerCode = !isExist;

            } error:^(NSError * _Nullable error) {

                [SVProgressHUD dismiss];
                self.numberWarningInfo = @"网络出错，请稍后再试";

            } completed:^{

                NSLog(@"completed");
            }];
        } else {

            // 当输入到达 11 位后 不是号码
            if (number.length == 11) {

                self.numberWarningInfo = @"请输入正确的手机号码";

            } else {

                self.numberWarningInfo = @"";
            }
            
            self.canVerCode = NO;
        }
    }];
    
    
    
    // 验证码
    _verCodeCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            @strongify(self)
            [[YZSignAPI apiGetUserMessage:self.number] subscribeNext:^(id  _Nullable x) {
                
                [subscriber sendNext:x];
                [subscriber sendCompleted];
            } error:^(NSError * _Nullable error) {

                [subscriber sendError:error];
                [subscriber sendCompleted];
            }];
            
            return [RACDisposable disposableWithBlock:^{}];
        }];
    }];
    [_verCodeCmd.executing subscribeNext:^(id executing) {
        
        @strongify(self)
        BOOL isExecuting = [executing boolValue];
        self.canVerCode = !isExecuting;
    }];
    
    
    
    // 注册按钮是否可用
    _registerSignal = [RACSignal combineLatest:@[RACObserve(self, canVerCode), RACObserve(self, verCode), RACObserve(self, password)] reduce:^id(id canVerCode, NSString *verCode, NSString *password){
        
        return @([canVerCode boolValue] && verCode.length && (password.length >= 6 && password.length <= 16));
    }];
    
    // 注册按钮点击事件
    _registerCmd = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            @strongify(self)
            [[YZSignAPI apiRegistUser:self.number password:self.password verCode:self.verCode uid:[YZUser sharedInstance].uniqueId] subscribeNext:^(NSDictionary *userInfo) {

                [[YZUser sharedInstance] storeUserToLocal:userInfo];
                [subscriber sendNext:[YZUser sharedInstance].uid];
                [subscriber sendCompleted];
                
            } error:^(NSError * _Nullable error) {

                [subscriber sendError:error];
                [subscriber sendCompleted];
            }];
            
            return [RACDisposable disposableWithBlock:^{}];
        }];
    }];
    
    
    // 微信注册
    _weChatCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            
            // 微信登录
            [OpenShare WeixinAuth:@"snsapi_userinfo" Success:^(NSDictionary *data) {
                
                // 授权成功后获取 code = 081O4pLe1dtZXr0DW6Me1qmxLe1O4pLf;
                NSLog(@"微信登录成功:\n%@",data);
                if (data && data[@"code"]) {
                    
                    // 登录后台注册
//                    NSString *code = data[@"code"];
//                    [[YZSignAPI apiWeChatLogin:code] subscribeNext:^(NSDictionary *data) {
//
//                        // 保存用户数据
//                        NSLog(@"%@", data);
//                        [subscriber sendNext:data];
//
//                    } error:^(NSError * _Nullable error) {
//
//                        NSLog(@"NSError: %@", error);
//                        [subscriber sendError:error];
//
//                    } completed:^{
//
//                        NSLog(@"completed");
//                        [subscriber sendCompleted];
//                    }];
                }
                
                [subscriber sendNext:data];
                [subscriber sendCompleted];
                
            } Fail:^(NSDictionary *message, NSError *error) {
                
                NSLog(@"微信登录失败:\n%@\n%@",message,error);
                [subscriber sendError:error];
            }];
            
            return [RACDisposable disposableWithBlock:^{}];
        }];
    }];
}

@end
